package com.risk.management.service.impl;

import com.risk.management.entity.User;
import com.risk.management.mapper.UserMapper;
import com.risk.management.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService, UserDetailsService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> getUsersByRole(Integer role) {
        return userMapper.selectByRole(role);
    }

    @Override
    @Transactional
    public boolean addUser(User user) {
        try {
            logger.info("开始添加新用户: {}", user.getUsername());
            
            // 基本参数验证
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                logger.error("添加用户失败: 用户名不能为空");
                return false;
            }
            
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                logger.error("添加用户失败: 密码不能为空");
                return false;
            }
            
            // 检查用户名是否已存在
            User existingUser = getUserByUsername(user.getUsername());
            if (existingUser != null) {
                logger.error("添加用户失败: 用户名 {} 已存在", user.getUsername());
                return false;
            }
            
            // 确保角色值正确
            if (user.getRole() == null || user.getRole() < 1 || user.getRole() > 3) {
                logger.warn("用户角色值无效 ({}), 设置为默认值 3", user.getRole());
                user.setRole(3); // 默认设置为团队成员
            }
            
            // 加密密码
            String encodedPassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(encodedPassword);
            
            // 设置创建时间和更新时间
            Date now = new Date();
            user.setCreateTime(now);
            user.setUpdateTime(now);
            
            // 插入用户记录
            int result = userMapper.insert(user);
            if (result > 0) {
                logger.info("用户 {} 添加成功，ID: {}", user.getUsername(), user.getId());
                return true;
            } else {
                logger.error("添加用户失败: 数据库插入返回 0");
                return false;
            }
        } catch (Exception e) {
            logger.error("添加用户过程中发生异常", e);
            throw e; // 重新抛出异常以便事务回滚
        }
    }

    @Override
    @Transactional
    public boolean updateUser(User user) {
        // 不更新密码，密码通过专门的方法更新
        User existingUser = getUserById(user.getId());
        if (existingUser == null) {
            return false;
        }
        
        // 设置更新时间
        user.setUpdateTime(new Date());
        
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean deleteUser(Long id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public boolean updatePassword(Long id, String newPassword) {
        // 加密新密码
        String encodedPassword = passwordEncoder.encode(newPassword);
        return userMapper.updatePassword(id, encodedPassword) > 0;
    }

    @Override
    public boolean validatePassword(String username, String password) {
        User user = getUserByUsername(username);
        if (user == null) {
            return false;
        }
        
        // 验证密码
        return passwordEncoder.matches(password, user.getPassword());
    }
    
    /**
     * 实现UserDetailsService接口的方法
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            logger.info("尝试加载用户: {}", username);
            
            User user = userMapper.selectByUsername(username);
            if (user == null) {
                logger.error("用户不存在: {}", username);
                throw new UsernameNotFoundException("用户名或密码错误");
            }
            
            // 创建权限列表
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            // 根据用户角色添加权限
            if (user.getRole() == 1) {
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            } else if (user.getRole() == 2) {
                authorities.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
            } else {
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            }
            
            logger.info("成功加载用户: {}, 角色: {}", username, authorities);
            
            // 创建Spring Security的User对象
            return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authorities
            );
        } catch (Exception e) {
            logger.error("加载用户时发生异常: {}", username, e);
            throw new UsernameNotFoundException("认证过程中发生错误", e);
        }
    }
} 